//
//  FillInfoVC.m
//  UHealth
//
//  Created by gjtxz on 15/1/15.
//  Copyright (c) 2015年 gjtx. All rights reserved.
//

#import "FillInfoVC.h"
#import "UUDatePicker.h"

#import "UIImageView+WebCache.h"

#import "LoginVC.h"
#import "RegisterVC.h"
#import "AppDelegate.h"
#import "iToast.h"
#import "UserObj.h"
#import "NavView.h"
#import "DBManage.h"
#import "NSString+BloodSugar.h"

#import "VPImageCropperViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>

#import "SSCheckBoxView.h"

#define ORIGINAL_MAX_WIDTH 640.0f
#define kFieldJX    35.f


#define kUserInfoDic            @"UserInfoDic"

#define kUserInfoName           @"UserInfoName"
#define kUserInfoSex            @"UserInfoSex"
#define kUserInfoAge            @"UserInfoAge"
#define kUserInfoHeight         @"UserInfoHeight"
#define kUserInfoWeight         @"UserInfoWeight"

@interface FillInfoVC ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate, UIActionSheetDelegate, VPImageCropperDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic,strong) UIImageView            *portraitImageView;//头像
@property (nonatomic,strong) UITextField            *fieldName;//名字
@property (nonatomic,strong) UIButton               *maleBtn;
@property (nonatomic,strong) UIButton               *femaleBtn;
@property (nonatomic,strong) UITextField            *fieldBirth;//出生年月
@property (nonatomic,strong) UITextField            *fieldHeight;//身高
@property (nonatomic,strong) UITextField            *fieldWeight;//体重

@property (nonatomic,strong) UserObj                *user;

@property (nonatomic,strong) UIPickerView           *hPick;
@property (nonatomic,strong) UIPickerView           *wPick;
@property (nonatomic,strong) SSCheckBoxView         *cbv;

@property (nonatomic,strong) UIImage                *myImg;

@end

@implementation FillInfoVC

-(id)init
{
    self = [super init];
    if (self) {
        self.view.backgroundColor = kBacColor;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NavView *nav = [[NavView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, kNavHeight) andTitleStr:kLocal(@"UHealth")];
    [self.view addSubview:nav];
    
    UIScrollView *mailScroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, kNavHeight, WIDTH, HEIGHT - kNavHeight)];
    [self.view addSubview:mailScroll];
    
    UILabel *hit1 = [[UILabel alloc]initWithFrame:CGRectMake(20, 5 , WIDTH-40, 20)];
    hit1.text = kLocal(@"hit1");
    hit1.font = [UIFont systemFontOfSize:12];
    [mailScroll addSubview:hit1];
    
    [mailScroll addSubview:self.portraitImageView];
    self.portraitImageView.image = [UIImage imageNamed:@"user"];
    
    UUDatePicker *datePicker
    = [[UUDatePicker alloc]initWithframe:CGRectMake(0, 0, WIDTH, 200)
                             PickerStyle:UUDateStyle_YearMonthDay
                             didSelected:^(NSString *year,
                                           NSString *month,
                                           NSString *day,
                                           NSString *hour,
                                           NSString *minute,
                                           NSString *weekDay) {
                                 _fieldBirth.text = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
                                 
                             }];
    datePicker.backgroundColor = kBacColor;
    datePicker.ScrollToDate = [NSDate dateFromString:@"2013-01-01" withFormat:@"YYYY-MM-dd"];
    
    _hPick = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    _hPick.delegate = self;
    _hPick.dataSource = self;
    _hPick.backgroundColor = kBacColor;
    [_hPick selectRow:30 inComponent:0 animated:NO];
    
    _wPick = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 0, 320, 200)];
    _wPick.delegate = self;
    _wPick.dataSource = self;
    _wPick.backgroundColor = kBacColor;
    [_wPick selectRow:9 inComponent:0 animated:NO];//设置选中行
    
    NSArray *imgArr = @[@"relation",@"sex",@"age",@"height",@"weight"];
    _fieldName = [[UITextField alloc]init];
    _fieldBirth = [[UITextField alloc]init];
    _fieldHeight = [[UITextField alloc]init];
    _fieldWeight = [[UITextField alloc]init];
    
    NSArray *fArr = @[_fieldName,[[UITextField alloc]init],_fieldBirth,_fieldHeight,_fieldWeight];
    NSArray *plaArr = @[kLocal(@"editHit1"),@"",kLocal(@"editHit2"),kLocal(@"editHit3"),kLocal(@"editHit4")];
    for (int i = 0; i < 5; i++) {
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(20,120+i*kFieldJX, kFieldJX, kFieldJX)];
        img.image = [UIImage imageNamed:imgArr[i]];
        [mailScroll addSubview:img];
        
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, 155+ i*kFieldJX, WIDTH - 40, 0.5)];
        lineView.backgroundColor = [UIColor grayColor];
        [mailScroll addSubview:lineView];
        if (i == 1) {
            continue;
        }
        UITextField *field = fArr[i];
        field.frame = CGRectMake(70, 120 + i*kFieldJX, WIDTH-90, 40);
        field.font = [UIFont systemFontOfSize:14.0];
        field.placeholder = plaArr[i];
        field.clearButtonMode = UITextFieldViewModeWhileEditing;
        if (i == 2) {
            field.inputView = datePicker;
        }
        if (i == 3) {
            field.inputView = _hPick;
        }
        if (i == 4) {
            field.inputView = _wPick;
        }
        [mailScroll addSubview:field];
    }
    
    _maleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _maleBtn.frame = CGRectMake(70, 120 + kFieldJX, 50, 40);
    [_maleBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
    [_maleBtn setTitle:kLocal(@"male") forState:UIControlStateNormal];
    [_maleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _maleBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [_maleBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _maleBtn.tag = 5;
    [mailScroll addSubview:_maleBtn];
    
    _femaleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _femaleBtn.frame = CGRectMake(120, 120 + kFieldJX, 50, 40);
    [_femaleBtn setImage:[UIImage imageNamed:@"female_line"] forState:UIControlStateNormal];
    [_femaleBtn setTitle:kLocal(@"female") forState:UIControlStateNormal];
    [_femaleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    _femaleBtn.titleLabel.font = [UIFont systemFontOfSize:14.0];
    [_femaleBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    _femaleBtn.tag = 6;
    [mailScroll addSubview:_femaleBtn];
    
    
    _user = [[DBManage sharedManager] getUserWithID:0];
    if (_user) {
        [_portraitImageView sd_setImageWithURL:[NSURL URLWithString:_user.headImg] placeholderImage:[UIImage imageNamed:@"user"]];
        _fieldName.text = _user.name;
        if (_user.sex) {
            [_maleBtn setImage:[UIImage imageNamed:@"male_line"] forState:UIControlStateNormal];
            [_femaleBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
        }
        _fieldBirth.text = _user.birthDate;
        _fieldHeight.text = [NSString stringWithFormat:@"%3d cm",(int)_user.height ];
        _fieldWeight.text = [NSString stringWithFormat:@"%3d kg",(int)_user.weight];
        
        datePicker.ScrollToDate = [NSDate dateFromString:_user.birthDate withFormat:@"YYYY-MM-dd"];
        if ((int)_user.height >=100) {
            [_hPick selectRow:(int)_user.height - 100 inComponent:0 animated:NO];
        }
        if ((int)_user.weight >=30) {
            [_wPick selectRow:(int)_user.weight - 30 inComponent:0 animated:NO];
        }
    }else{
        _user = [[UserObj alloc]init];
        _user.headImg = @"";
        _user.userID = kNetID;
        _user.famID = 0;
        //        _portraitImageView.image = [UIImage imageWithContentsOfFile:kImgFilePath(-1)];
    }
    
    _cbv = [[SSCheckBoxView alloc] initWithFrame:CGRectMake(20,300 , 150, 21)
                                           style:kSSCheckBoxViewStyleGlossy
                                         checked:YES];
    [_cbv setText:kLocal(@"read_and_accept")];
    [mailScroll addSubview:_cbv];
    
    UIButton *lBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lBtn.frame = CGRectMake(145, 308, 80 , 22);
    [lBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    lBtn.tag = 4;
    lBtn.backgroundColor = [UIColor clearColor];
    lBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:kLocal(@"disclaimer")];
    NSRange strRange = {0,[str length]};
    [str addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:strRange];
    [lBtn setAttributedTitle:str forState:UIControlStateNormal];
    //    [lBtn setTitle:@"《免责条款》" forState:UIControlStateNormal];
    [lBtn setTitleColor:kBlueColor forState:UIControlStateNormal];
    [mailScroll addSubview:lBtn];
    
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(60, 335, WIDTH/2 -70, 35);
    [loginBtn setTitle:kLocal(@"login") forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    loginBtn.tag = 1;
    [loginBtn.layer setMasksToBounds:YES];
    [loginBtn.layer setCornerRadius:5.0];//设置矩形是个圆角半径
    loginBtn.backgroundColor = [UIColor grayColor];
    [mailScroll addSubview:loginBtn];
    
    UIButton *regBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    regBtn.frame = CGRectMake(WIDTH/2 + 10, 335, WIDTH/2 -70, 35);
    [regBtn setTitle:kLocal(@"register") forState:UIControlStateNormal];
    [regBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [regBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    regBtn.tag = 2;
    [regBtn.layer setMasksToBounds:YES];
    [regBtn.layer setCornerRadius:5.0];//设置矩形是个圆角半径
    regBtn.backgroundColor = [UIColor grayColor];
    [mailScroll addSubview:regBtn];
    
    UILabel *hit2 = [[UILabel alloc]initWithFrame:CGRectMake(20, 380, WIDTH-40, 20)];
    hit2.text = kLocal(@"hit2");
    hit2.font = [UIFont systemFontOfSize:12];
    [mailScroll addSubview:hit2];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(20, 403, WIDTH - 40, 0.5)];
    lineView.backgroundColor = [UIColor grayColor];
    [mailScroll addSubview:lineView];
    
    UIButton *enterBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    enterBtn.frame = CGRectMake(40, 430, WIDTH - 80, 44);
    [enterBtn setTitle:kLocal(@"enter") forState:UIControlStateNormal];
    [enterBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [enterBtn addTarget:self action:@selector(BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    enterBtn.tag = 3;
    [enterBtn.layer setMasksToBounds:YES];
    [enterBtn.layer setCornerRadius:1.0];//设置矩形是个圆角半径
    enterBtn.backgroundColor = kBlueColor;
    [mailScroll addSubview:enterBtn];
    
    
    mailScroll.contentSize = CGSizeMake(WIDTH, enterBtn.frame.size.height + enterBtn.frame.origin.y+30);
    
 }

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)BtnClick:(UIButton *)btn
{
    NSString *name = _fieldName.text;
    NSString *birthDate = _fieldBirth.text;
    NSString *height = _fieldHeight.text;
    NSString *weight = _fieldWeight.text;
    
    if ((!name.length || !birthDate.length || !height.length || !weight.length) && btn.tag < 4 &&btn.tag!=1) {
        [[iToast makeText:kLocal(@"infoHit")] show];
        return;
    }
    
    if (!_cbv.checked && btn.tag < 4 ) {
        [[iToast makeText:kLocal(@"mianze")] show];
        return;
    }
    [self.view endEditing:YES];
    switch (btn.tag) {
        case 1:{
            [self presentViewController:[[LoginVC alloc]init] animated:YES completion:nil];
        }
            break;
        case 2:{
            _user.name = name;
            _user.birthDate = birthDate;
            _user.height = [[height substringToIndex:3] floatValue];
            _user.weight = [[weight substringToIndex:3] floatValue];
            
            RegisterVC *reg = [[RegisterVC alloc]init];
            reg.user = _user;
            reg.myImg = _myImg;
            [self presentViewController:reg animated:YES completion:nil];
        }
            break;
        case 3:{
            _user.name = name;
            _user.birthDate = birthDate;
            _user.height = [[height substringToIndex:3] floatValue];
            _user.weight = [[weight substringToIndex:3] floatValue];
            //插入或者更新
            
            if (![[DBManage sharedManager] getUserWithID:_user.famID]) {// 第一次
                [[DBManage sharedManager]insertData:_user andTable:kUserTable];
            }else{//若存在则更新
                NSString *setStr = [NSString stringWithFormat:@"%@ = '%@',%@ = '%@',%@ = '%d',%@ = '%@',%@ = '%f',%@ = '%f'",kUserHeadImg,_user.headImg,kUserName,_user.name,kUserSex,_user.sex,kUserBirthDate,_user.birthDate,kUserHeight,_user.height,kUserWeight,_user.weight];
                NSString *conStr = [NSString stringWithFormat:@"%@ = '%d' ",kFamID,_user.famID];
                [[DBManage sharedManager] updateData:setStr andTable:kUserTable andConditions:conStr];
            }

            
            AppDelegate *delegate = [UIApplication sharedApplication].delegate;
            [delegate changRootVCToMain];
        }
            break;
        case 4:
        {
            [[iToast makeText:btn.titleLabel.text]show];
        }
            break;
        case 5:
            _user.sex = 0;
            [_maleBtn setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
            [_femaleBtn setImage:[UIImage imageNamed:@"female_line"] forState:UIControlStateNormal];
            break;
        case 6:
            _user.sex = 1;
            [_maleBtn setImage:[UIImage imageNamed:@"male_line"] forState:UIControlStateNormal];
            [_femaleBtn setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
            break;
        default:
            break;
    }
}


#pragma mark - 选择器

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        return 120;
    }
    return 150;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        return [NSString stringWithFormat:@"%3d kg",6 + (int)row];
    }
    return  [NSString stringWithFormat:@"%3d cm",60 + (int)row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if ([_wPick isEqual:pickerView]) {
        _fieldWeight.text = [NSString stringWithFormat:@"%3d kg",6 +(int)row];
    }else{
        _fieldHeight.text = [NSString stringWithFormat:@"%3d cm",60 + (int)row];
    }
    
}

#pragma mark - 触摸

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.view endEditing:YES];
}

#pragma mark - 头像

#pragma mark portraitImageView getter
- (UIImageView *)portraitImageView {
    if (!_portraitImageView) {
        CGFloat w = 80.f; CGFloat h = w;
        CGFloat x = (WIDTH - w)/2;
        CGFloat y = 30;
        _portraitImageView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, w, h)];
        [_portraitImageView.layer setCornerRadius:(_portraitImageView.frame.size.height/2)];
        [_portraitImageView.layer setMasksToBounds:YES];
        [_portraitImageView setContentMode:UIViewContentModeScaleAspectFill];
        [_portraitImageView setClipsToBounds:YES];
        _portraitImageView.layer.shadowColor = kBlueColor.CGColor;
        _portraitImageView.layer.shadowOffset = CGSizeMake(4, 4);
        _portraitImageView.layer.shadowOpacity = 0.5;
        _portraitImageView.layer.shadowRadius = 2.0;
        _portraitImageView.layer.borderColor = [kBlueColor CGColor];
        _portraitImageView.layer.borderWidth = 1.0f;
        _portraitImageView.userInteractionEnabled = YES;
        _portraitImageView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(editPortrait)];
        [_portraitImageView addGestureRecognizer:portraitTap];
    }
    return _portraitImageView;
}

- (void)editPortrait {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:kLocal(@"cancel")
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:kLocal(@"take_pic"), kLocal(@"select_from_album"), nil];
    [choiceSheet showInView:self.view];
}

#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {
    self.portraitImageView.image = editedImage;
    _myImg = editedImage;
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
        // TO DO
    }];
    //    [UIImagePNGRepresentation(editedImage) writeToFile: kPostImgFilePath  atomically:YES];
}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    [cropperViewController dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        // 拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                controller.cameraDevice = UIImagePickerControllerCameraDeviceFront;
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                             }];
        }
        
    } else if (buttonIndex == 1) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            UIImagePickerController *controller = [[UIImagePickerController alloc] init];
            controller.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            controller.mediaTypes = mediaTypes;
            controller.delegate = self;
            [self presentViewController:controller
                               animated:YES
                             completion:^(void){
                             }];
        }
    }
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:^() {
        UIImage *portraitImg = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        portraitImg = [self imageByScalingToMaxSize:portraitImg];
        // 裁剪
        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width, self.view.frame.size.width) limitScaleRatio:3.0];
        imgEditorVC.delegate = self;
        [self presentViewController:imgEditorVC animated:YES completion:^{
            // TO DO
        }];
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}


#pragma mark camera utility
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}

#pragma mark image scale utility
- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {
    if (sourceImage.size.width < ORIGINAL_MAX_WIDTH) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = ORIGINAL_MAX_WIDTH;
        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);
    } else {
        btWidth = ORIGINAL_MAX_WIDTH;
        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        kDebug(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
